import { createParameterDecorator } from "maishu-node-mvc"
import { createConnection, getConnection, ConnectionOptions, getConnectionManager } from "typeorm";
// import { config } from "./config";
import path = require("path");
import { settings } from "./common";

export let connection = createParameterDecorator(async () => {
    let connectionManager = getConnectionManager();
    if (!connectionManager.has(settings.db.database)) {
        let dbOptions: ConnectionOptions = {
            type: "mysql",
            host: settings.db.host,
            port: settings.db.port,
            username: settings.db.user,
            password: settings.db.password,
            database: settings.db.database,
            synchronize: true,
            logging: true,
            entities: [path.join(__dirname, "entities.js")],
            name: settings.db.database,
        }

        await createConnection(dbOptions)
    }
    let connection = getConnection(settings.db.database);
    return Promise.resolve(connection);
}) as Function;

